import sys
import pandas as pd
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QWidget, \
    QLineEdit, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, \
    QScrollArea, QGroupBox, QCheckBox, QProgressBar

from parse_course import ParseCourse


class MyThread(QThread):
    my_signal = pyqtSignal()

    def __init__(self, file_name, cursor_parser):
        super(MyThread, self).__init__()
        self.file_name = file_name
        self.cursor_parser = cursor_parser

    def run(self):
        print("start...")
        self.cursor_parser.handle_sheet(self.cursor_parser.unmerge_cell(self.file_name))
        self.my_signal.emit()
        print("end")


# 主窗口
class Main(QWidget):
    def __init__(self):
        super().__init__()
        self.btn_clear = None
        self.lb3 = None
        self.hl = None
        self.th = None
        self.cbvl = None
        self.sa = None
        self.gb = None
        self.lb2 = None
        self.btn = None
        self.lb = None
        self.vl = None
        self.le = None
        self.file_path = None
        self.setWindowTitle('课表解析(拖入课表文件)')
        self.resize(960, 720)
        self.init_ui()
        self.setAcceptDrops(True)
        self.curse_parser = ParseCourse()
        self.init_progress_signal()

    def init_ui(self):
        self.vl = QVBoxLayout(self)
        self.lb = QLabel("文件路径:", self)
        self.lb2 = QLabel("", self)
        self.le = QLineEdit(self)
        self.sa = QScrollArea()
        self.btn = QPushButton("开始解析")
        self.btn.setEnabled(False)
        self.btn.clicked.connect(self.btn_handle)

        self.hl = QHBoxLayout()
        self.lb3 = QLabel('已选: ' + '0')
        self.btn_clear = QPushButton('清除已选')
        self.btn_clear.clicked.connect(self.check_clear)
        self.hl.addWidget(self.lb3)
        self.hl.addStretch()
        self.hl.addWidget(self.btn_clear)

        # 进度条
        self.hl2 = QHBoxLayout()
        self.prg = QProgressBar()
        self.prg.setMaximum(200)
        self.prg.setValue(0)
        self.hl2.addWidget(self.prg)

        self.vl.addWidget(self.lb)
        self.vl.addWidget(self.le)
        self.vl.addWidget(self.btn)
        # self.vl.addStretch()
        self.vl.addWidget(self.sa)
        self.vl.addLayout(self.hl)
        self.vl.addLayout(self.hl2)
        self.vl.addWidget(self.lb2)
        self.setLayout(self.vl)

    # 展示可选的sheet
    def show_sheet_names(self, file_name):
        pf = pd.ExcelFile(file_name)
        self.gb = QGroupBox()
        self.gb.setTitle('班级选择')
        self.cbvl = QVBoxLayout()
        for sheet in pf.sheet_names:
            cb = QCheckBox(sheet)
            cb.stateChanged.connect(self.checkbox_state_changed)
            self.cbvl.addWidget(cb)

        self.gb.setLayout(self.cbvl)
        self.vl.addWidget(self.gb)
        self.sa.setWidget(self.gb)

    # 开始解析
    def btn_handle(self):
        self.curse_parser.clear_data()
        self.prg.setValue(0)

        checkBoxs = self.gb.findChildren(QCheckBox)
        for checkbox in checkBoxs:
            if checkbox.isChecked():
                self.curse_parser.chkClass.append(checkbox.text())
        print('checked class:', self.curse_parser.chkClass)
        self.btn.setEnabled(False)
        if len(self.curse_parser.chkClass) > 0:
            self.prg.setMaximum(len(self.curse_parser.chkClass))
        else:
            self.prg.setMaximum(len(checkBoxs))

        self.th = MyThread(self.le.text(), self.curse_parser)
        self.th.my_signal.connect(self.done)
        self.th.start()
        self.lb2.setText("解析中...")

    # 统计选择班级的数量
    def sum_check(self):
        c = 0
        checkBoxs = self.gb.findChildren(QCheckBox)
        for checkbox in checkBoxs:
            if checkbox.isChecked():
                c += 1
        return c

    # 初始化进度条信号
    def init_progress_signal(self):
        self.curse_parser.progress_max_sig.connect(self.set_prg_max)
        self.curse_parser.parse_progress_sig.connect(self.set_prg_value)

    # 设置进度条最大值
    def set_prg_max(self, max_v):
        self.prg.setMaximum(max_v)

    # 修改进度条
    def set_prg_value(self, cur_v):
        self.prg.setValue(cur_v)

    # 清除已选
    def check_clear(self):
        self.curse_parser.clear_data()
        checkBoxs = self.gb.findChildren(QCheckBox)
        for checkbox in checkBoxs:
            checkbox.setCheckState(False)

    # 线程任务完成
    def done(self):
        self.lb2.setText("解析完成!")
        self.btn.setEnabled(True)

    def checkbox_state_changed(self, checked):
        self.lb3.setText('已选: ' + str(self.sum_check()))

    # 鼠标拖入事件
    def dragEnterEvent(self, evn):
        # 鼠标放开函数事件
        evn.accept()

    # 鼠标放开执行
    def dropEvent(self, evn):
        self.le.setText(evn.mimeData().text().replace('file:///', '', 1))
        self.file_path = evn.mimeData().text().replace('file:///', '', 1)
        self.show_sheet_names(self.file_path)
        self.btn.setEnabled(True)
        self.lb2.setText("")

    def dragMoveEvent(self, evn):
        print('鼠标移入')


if __name__ == "__main__":
    app = QApplication(sys.argv)
    e = Main()
    e.show()
    sys.exit(app.exec_())
